import sys
import os
from PyQt6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, 
                             QPushButton, QProgressBar, QListWidget, 
                             QFileDialog, QLabel, QSizePolicy, QDialog,
                             QFormLayout, QLineEdit, QComboBox)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon
from openpyxl import Workbook, load_workbook 
from datetime import datetime  # Import datetime to get the current month

class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("系统设置")
        self.setFixedSize(400, 300)
        
        layout = QVBoxLayout()
        
        # 设置表单
        form_layout = QFormLayout()
        
        # 新增月份选择组件
        self.month_combo = QComboBox()
        current_month = datetime.now().month
        month_names = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
        self.month_combo.addItems(month_names)
        self.month_combo.setCurrentIndex(current_month - 1)  # Set default to current month
        form_layout.addRow("选择月份:", self.month_combo)
        
        # 原有的界面主题选择组件
        self.theme_combo = QComboBox()
        self.theme_combo.addItems(["默认主题", "深色主题", "蓝色主题"])
        form_layout.addRow("界面主题:", self.theme_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存设置")
        self.save_btn.clicked.connect(self.accept)
        btn_layout.addWidget(self.save_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(btn_layout)
        self.setLayout(layout)
        
        self.setStyleSheet("""
            QDialog {
                background-color: #f5f5f5;
            }
            QLabel {
                font-size: 14px;
            }
            QLineEdit, QComboBox {
                padding: 5px;
                font-size: 14px;
                border: 1px solid #ddd;
                border-radius: 3px;
            }
        """)

class ExcelProcessor(QWidget):
    def __init__(self):
        super().__init__()
        # 设置无边框窗口
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        
        self.setWindowTitle("附属医院月度算薪")
        self.setGeometry(100, 100, 800, 600)
        self.setWindowIcon(QIcon("icon.png"))
        
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 顶部工具栏（包含标题和按钮）
        top_toolbar = QHBoxLayout()
        top_toolbar.setContentsMargins(0, 0, 0, 10)
        
        # 添加标题
        title_label = QLabel("附属医院月度算薪系统")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        top_toolbar.addWidget(title_label)
        
        # 添加弹簧使按钮靠右
        top_toolbar.addStretch()
        
        # 添加设置按钮
        self.settings_btn = QPushButton("⚙")  # 使用齿轮符号
        self.settings_btn.setFixedSize(30, 30)
        self.settings_btn.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: white;
                border-radius: 15px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #64b5f6;
            }
        """)
        self.settings_btn.clicked.connect(self.show_settings)
        top_toolbar.addWidget(self.settings_btn)
        
        # 添加关闭按钮（右侧）
        self.close_btn = QPushButton("×")
        self.close_btn.setFixedSize(30, 30)
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff4d4d;
                color: white;
                border-radius: 15px;
                font-size: 18px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
        """)
        self.close_btn.clicked.connect(self.close)
        top_toolbar.addWidget(self.close_btn)
        
        main_layout.addLayout(top_toolbar)
        
        # 文件选择区域
        file_group = self.create_file_group()
        main_layout.addLayout(file_group)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.progress_bar.setFixedHeight(30)
        main_layout.addWidget(self.progress_bar)
        
        # 列表显示
        self.list_widget = QListWidget()
        self.list_widget.setMinimumHeight(300)
        main_layout.addWidget(self.list_widget)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 0)
        
        self.process_btn = QPushButton("开始处理")
        self.process_btn.setFixedSize(150, 40)
        self.process_btn.clicked.connect(self.process_files)  # 确保方法正确连接
        button_layout.addWidget(self.process_btn)
        
        button_layout.addSpacing(20)  # 添加间距
        
        self.clear_btn = QPushButton("清空列表")
        self.clear_btn.setFixedSize(150, 40)
        self.clear_btn.clicked.connect(self.clear_list)
        button_layout.addWidget(self.clear_btn)
        
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
        self.setStyleSheet(self.get_stylesheet())
        
        # 窗口拖动相关变量
        self.drag_start_position = None
        self.folder_path = ""  # 初始化文件夹路径
        self.selected_file_path = ""  # 初始化选择的文件路径
    
    def show_settings(self):
        """显示设置对话框"""
        settings_dialog = SettingsDialog(self)
        if settings_dialog.exec() == QDialog.DialogCode.Accepted:
            selected_month = settings_dialog.month_combo.currentText()
            selected_theme = settings_dialog.theme_combo.currentText()
            self.list_widget.addItem(f"设置已保存 - 月份: {selected_month}, 主题: {selected_theme}")
    
    def create_file_group(self):
        group_layout = QVBoxLayout()
        group_layout.setSpacing(15)
        
        # 文件选择
        file_btn_layout = QHBoxLayout()
        self.file_label = QLabel("未选择文件")
        self.file_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        self.file_btn = QPushButton("选择Excel文件")
        self.file_btn.setFixedSize(150, 40)
        self.file_btn.clicked.connect(self.select_file)
        file_btn_layout.addWidget(self.file_btn)
        file_btn_layout.addWidget(self.file_label)
        
        # 文件夹选择
        folder_btn_layout = QHBoxLayout()
        self.folder_label = QLabel("未选择文件夹")
        self.folder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        self.folder_btn = QPushButton("选择输出文件夹")
        self.folder_btn.setFixedSize(150, 40)
        self.folder_btn.clicked.connect(self.select_folder)
        folder_btn_layout.addWidget(self.folder_btn)
        folder_btn_layout.addWidget(self.folder_label)
        
        group_layout.addLayout(file_btn_layout)
        group_layout.addLayout(folder_btn_layout)
        
        return group_layout
    
    def select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择Excel文件", 
            "", 
            "Excel文件 (*.xlsx *.xls)"
        )
        if file_path:
            self.file_label.setText(file_path.split('/')[-1])
            self.selected_file_path = file_path  # 保存选择的文件路径
            self.list_widget.addItem(f"已选择文件: {file_path}")
    
    def select_folder(self):
        folder_path = QFileDialog.getExistingDirectory(
            self,
            "选择输出文件夹"
        )
        if folder_path:
            self.folder_path = folder_path  # 保存文件夹路径
            self.folder_label.setText(folder_path)
            self.list_widget.addItem(f"输出目录: {folder_path}")
    
    def process_files(self):
        self.progress_bar.setValue(0)
        self.list_widget.addItem("开始处理文件...")

        # 检查是否已选择输出文件夹
        if not self.folder_path:
            self.list_widget.addItem("错误：请先选择输出文件夹")
            self.progress_bar.setValue(0)
            return

        try:
            # 创建新的工作簿
            wb = Workbook()
            master_file = os.path.join(self.folder_path, "考勤统计.xlsx")
            wb.save(master_file)
            self.list_widget.addItem(f"已创建考勤表格模板: {master_file}")
        except Exception as e:
            self.list_widget.addItem(f"错误：{str(e)}")
            self.progress_bar.setValue(0)
            return

        # 遍历文件夹中的Excel文件并合并数据
        self.list_widget.addItem("开始合并数据...")
        processed_files = 0

        for file in os.listdir(self.folder_path):
            if file.endswith(('.xlsx', '.xls')) and file != "考勤统计.xlsx":
                file_path = os.path.join(self.folder_path, file)
                try:
                    src_wb = load_workbook(file_path)
                    
                    for src_sheet_name in src_wb.sheetnames:
                        src_ws = src_wb[src_sheet_name]
                        
                        # 如果目标工作簿中没有这个sheet，则创建一个
                        if src_sheet_name not in wb.sheetnames:
                            wb.create_sheet(title=src_sheet_name)
                        master_ws = wb[src_sheet_name]
                        
                        # 获取当前主文件的最新行号
                        current_row = master_ws.max_row + 1 if master_ws.max_row > 1 else 1
                        
                        # 复制整行数据到主文件
                        for row in range(1, src_ws.max_row + 1):
                            # 检查是否空行
                            if not any(src_ws.cell(row=row, column=col).value for col in range(1, src_ws.max_column + 1)):
                                continue
                            
                            # 复制整行数据到主文件
                            for col in range(1, src_ws.max_column + 1):
                                master_ws.cell(row=current_row, column=col, value=src_ws.cell(row=row, column=col).value)
                            
                            current_row += 1
                        
                        processed_files += 1
                        self.list_widget.addItem(f"已合并文件: {file} 的表: {src_sheet_name}")
                        
                except Exception as e:
                    self.list_widget.addItem(f"处理文件 {file} 出错: {str(e)}")

        # 复制选择的Excel文件中的第一个表单到新的“薪酬调查”表
        if self.selected_file_path:
            try:
                src_wb = load_workbook(self.selected_file_path)
                if src_wb.sheetnames:
                    first_sheet_name = src_wb.sheetnames[0]
                    src_ws = src_wb[first_sheet_name]
                    
                    if "薪酬调查" not in wb.sheetnames:
                        wb.create_sheet(title="薪酬调查")
                    salary_survey_ws = wb["薪酬调查"]
                    
                    # 复制整行数据到新的“薪酬调查”表
                    for row in range(1, src_ws.max_row + 1):
                        for col in range(1, src_ws.max_column + 1):
                            salary_survey_ws.cell(row=row, column=col, value=src_ws.cell(row=row, column=col).value)
                    
                    self.list_widget.addItem(f"已复制文件: {self.file_label.text()} 的第一个表单到“薪酬调查”表")
            except Exception as e:
                self.list_widget.addItem(f"处理选择的文件 {self.file_label.text()} 出错: {str(e)}")

        # 保存合并后的数据
        if processed_files > 0:
            wb.save(master_file)
            self.list_widget.addItem(f"成功合并 {processed_files} 个文件的数据")
        else:
            self.list_widget.addItem("未找到可合并的Excel文件")
    
    def clear_list(self):
        self.list_widget.clear()
        self.file_label.setText("未选择文件")
        self.folder_label.setText("未选择文件夹")
        self.progress_bar.setValue(0)
        self.folder_path = ""  # 清空文件夹路径
        self.selected_file_path = ""  # 清空选择的文件路径
    
    def mousePressEvent(self, event):
        """实现窗口拖动功能"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.drag_start_position = event.globalPosition().toPoint()
    
    def mouseMoveEvent(self, event):
        """实现窗口拖动功能"""
        if hasattr(self, 'drag_start_position') and self.drag_start_position:
            delta = event.globalPosition().toPoint() - self.drag_start_position
            self.move(self.pos() + delta)
            self.drag_start_position = event.globalPosition().toPoint()
    
    def mouseReleaseEvent(self, event):
        """清除拖动状态"""
        if hasattr(self, 'drag_start_position'):
            self.drag_start_position = None
    
    def get_stylesheet(self):
        return """
            QWidget {
                background-color: #f5f5f5;
                font-family: 'Microsoft YaHei';
            }
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 5px;
                padding: 8px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QLabel {
                font-size: 14px;
                color: #333;
                padding: 5px;
            }
            QProgressBar {
                border: 1px solid #ccc;
                border-radius: 5px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #4CAF50;
                width: 10px;
            }
            QListWidget {
                background-color: white;
                border: 1px solid #ddd;
                border-radius: 5px;
                padding: 10px;
                font-size: 14px;
            }
        """

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ExcelProcessor()
    window.show()
    sys.exit(app.exec())
